/*
 *  Copyright 2008 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.antext.core.generate;

import xdoclet.XDocletException;
import xdoclet.tagshandler.TypeTagsHandler;
import xjavadoc.Type;
import xjavadoc.XClass;

import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * Provides some useful XDoclet tags used for code generation.
 * <p><a href="GenTagsHandler.java.html"><i>View source</i></a></p>
 *
 * @author Roman Puchkovskiy <a href="mailto:roman.puchkovskiy@blandware.com">
 *         &lt;roman.puchkovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.2 $ $Date: 2008/04/30 17:16:27 $
 */
public class GenTagsHandler extends TypeTagsHandler {

    public static final Set PRIMITIVE_TYPES = new HashSet();
    static {
        PRIMITIVE_TYPES.add("boolean");
        PRIMITIVE_TYPES.add("byte");
        PRIMITIVE_TYPES.add("char");
        PRIMITIVE_TYPES.add("short");
        PRIMITIVE_TYPES.add("int");
        PRIMITIVE_TYPES.add("long");
        PRIMITIVE_TYPES.add("float");
        PRIMITIVE_TYPES.add("double");
    }

    public static final Set WRAPPER_TYPES = new HashSet();
    static {
        WRAPPER_TYPES.add(Boolean.class.getName());
        WRAPPER_TYPES.add(Byte.class.getName());
        WRAPPER_TYPES.add(Character.class.getName());
        WRAPPER_TYPES.add(Short.class.getName());
        WRAPPER_TYPES.add(Integer.class.getName());
        WRAPPER_TYPES.add(Long.class.getName());
        WRAPPER_TYPES.add(Float.class.getName());
        WRAPPER_TYPES.add(Double.class.getName());
    }

    public static final Set NUMBER_TYPES = new HashSet();
    static {
        NUMBER_TYPES.add("byte");
        NUMBER_TYPES.add(Byte.class.getName());
        NUMBER_TYPES.add("short");
        NUMBER_TYPES.add(Short.class.getName());
        NUMBER_TYPES.add("int");
        NUMBER_TYPES.add(Integer.class.getName());
        NUMBER_TYPES.add("long");
        NUMBER_TYPES.add(Long.class.getName());
        NUMBER_TYPES.add("float");
        NUMBER_TYPES.add(Float.class.getName());
        NUMBER_TYPES.add("double");
        NUMBER_TYPES.add(Double.class.getName());
    }

    protected Map counters = new HashMap();

    /**
     * Public default constructor.
     */
    public GenTagsHandler() {
    }

    /**
     * Renders template if current method return type (or property type) is
     * number (i.e. one of primitive or wrapped numeric types).
     *
     * @param template  template to render
     * @throws XDocletException thrown on error
     */
    public void ifIsNumber(String template) throws XDocletException {
        Type type = getCurrentMethod().getReturnType();

        XClass currentType = type.getType();
        String curDimStr = type.getDimensionAsString();

        if (!"".equals(curDimStr)) {
            return;
        }

        int extent = TypeTagsHandler.TYPE_CONCRETE_TYPE;
        if (isOneOfType(currentType, NUMBER_TYPES, extent)) {
            generate(template);
        }
    }

    /**
     * Renders template if current method return type (or property type) is
     * primitive type, primitive type wrapper or string.
     *
     * @param template  template to render
     * @throws XDocletException thrown on error
     */
    public void ifIsPrimitiveOrWrapperOrString(String template) throws XDocletException {
        Type type = getCurrentMethod().getReturnType();

        XClass currentType = type.getType();
        String curDimStr = type.getDimensionAsString();

        if (!"".equals(curDimStr)) {
            return;
        }

        int extent = TypeTagsHandler.TYPE_CONCRETE_TYPE;
        if (isOneOfType(currentType, PRIMITIVE_TYPES, extent)
                || isOneOfType(currentType, WRAPPER_TYPES, extent)
                || isOfType(currentType, String.class.getName(), extent)) {
            generate(template);
        }
    }

    /**
     * Renders template if current method return type (or property type) is
     * java.util.Date.
     *
     * @param template  template to render
     * @throws XDocletException thrown on error
     */
    public void ifIsPrimitiveOrWrapperOrStringOrDate(String template) throws XDocletException {
        Type type = getCurrentMethod().getReturnType();

        XClass currentType = type.getType();
        String curDimStr = type.getDimensionAsString();

        if (!"".equals(curDimStr)) {
            return;
        }

        int extent = TypeTagsHandler.TYPE_CONCRETE_TYPE;
        if (isOneOfType(currentType, PRIMITIVE_TYPES, extent)
                || isOneOfType(currentType, WRAPPER_TYPES, extent)
                || isOfType(currentType, String.class.getName(), extent)
                || isOfType(currentType, Date.class.getName(), extent)) {
            generate(template);
        }
    }

    /**
     * Returns true if given type is one of types given as a set.
     *
     * @param type      type to check
     * @param typeNames type names
     * @param extent    extent (concrete type, supertype, hierarchy)
     * @return true if type is one of supplied
     */
    public static boolean isOneOfType(XClass type, Set typeNames, int extent) {
        Iterator it = typeNames.iterator();
        while (it.hasNext()) {
            String typeName = (String) it.next();
            if (isOfType(type, typeName, extent)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Creates a counter.
     *
     * @param properties    supplies tag attributes ('name' is defined here)
     * @throws XDocletException thrown on error
     */
    public void createCounter(Properties properties) throws XDocletException {
        String name = (String) properties.get("name");
        if (name == null) {
            throw new XDocletException("name should be specified");
        }
        if (counters.containsKey(name)) {
            throw new XDocletException("counter named " + name + " already exists");
        }
        String initialValueString = (String) properties.get("initialValue");
        Integer initialValue;
        if (initialValueString == null) {
            initialValue = Integer.valueOf(0);
        } else {
            initialValue = Integer.valueOf(initialValueString);
        }
        counters.put(name, initialValue);
    }

    /**
     * Increments an existing counter.
     *
     * @param properties    supplies tag attributes ('name' is defined here)
     * @throws XDocletException thrown on error
     */
    public void incrementCounter(Properties properties) throws XDocletException {
        String name = (String) properties.get("name");
        if (name == null) {
            throw new XDocletException("name should be specified");
        }
        if (!counters.containsKey(name)) {
            throw new XDocletException("unknown counter: " + name);
        }
        counters.put(name, Integer.valueOf(((Integer) counters.get(name)).intValue() + 1));
    }

    /**
     * Returns counter value.
     *
     * @param properties    supplies tag attributes ('name' is defined here)
     * @return counter value
     * @throws XDocletException thrown on error
     */
    public String getCounter(Properties properties) throws XDocletException {
        String name = (String) properties.get("name");
        if (name == null) {
            throw new XDocletException("name should be specified");
        }
        if (!counters.containsKey(name)) {
            throw new XDocletException("unknown counter: " + name);
        }
        return counters.get(name).toString();
    }
}
